from django.core.urlresolvers import reverse
from sitepal.sitebase.conf    import properties
from urllib                   import urlencode
from urlparse                 import urlparse,urlunparse,parse_qs

def link_attributes(self,attributes):
    output = []
    output.append(self.render_attribute('href',attributes['href']))
    output.append(self.common_attributes(attributes))
    return u''.join(output)

def render_link_queries(self,*queries):
    output = {}
    for query in queries:
        for name,value in query.iteritems():
            if isinstance(value,(list,tuple)) and len(value) == 1:
                value = value[0]
            output[name] = value
    return urlencode(output)

def render_link(self,content=None,url=None,resolve=None,attributes={},query={}):
    if url and content:
        result    = urlparse(url)
        query_str = self.render_link_queries(parse_qs(result[4]),query)
        if resolve == 'menu':
            try:
                name               = properties.get('menu-views-url-reverse-name',admin=True)
                kwarg              = properties.get('menu-views-url-reverse-kwarg',admin=True)
                path               = reverse(name,kwargs={kwarg:self.safe_url_path(result[2])})
                attributes['href'] = urlunparse((result[0],result[1],path,result[3],query_str,
                                                 result[5]))
            except AttributeError:
                return u''
        elif resolve == 'media':
            attributes['href'] = urlunparse((result[0],result[1],self.get_medium_url(result[2]),
                                             result[3],query_str,result[5]))
        else:
            attributes['href'] = urlunparse((result[0],result[1],result[2],result[3],query_str,
                                             result[5]))
        return self.render_tag('a',content,attributes,render_attributes=self.link_attributes)
    return u''

def render_links(self,links=None,title=None,attributes={},list_type='ul',title_type='h3',
                 content=None,url=None,resolve=None):
    def render_content(item):
        if isinstance(item,(list,tuple)):
            return self.render_link(*item)
        elif isinstance(item,dict):
            return self.render_link(**item)
        else:
            raise ValueError,"Link item data must be either a list, tuple or dict"

    return self.render_list(links,title,attributes,list_type,title_type,render_content)

